package com.example.errorcodehelper.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.errorcodehelper.bean.param.CreateCodeParam;
import com.example.errorcodehelper.bean.param.UpdateCodeParam;
import com.example.errorcodehelper.bean.po.ErrorCode;
import com.example.errorcodehelper.bean.po.PreErrorCode;
import com.example.errorcodehelper.service.ErrorCodeService;
import com.example.errorcodehelper.service.PreErrorCodeService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.NumberFormat;
import java.util.List;

@RestController
@RequestMapping(value ="/code" )
public class ErrorCodeController {

    @Resource
    RedisTemplate redisTemplate;
    @Resource
    ErrorCodeService errorCodeService;
    @Resource
    PreErrorCodeService preErrorCodeService;

    @RequestMapping(value = "/create",method = RequestMethod.POST)
    public String CreateCode(@RequestBody CreateCodeParam createCodeParam){

        //前两位
        PreErrorCode one = preErrorCodeService.getOne(Wrappers.<PreErrorCode>lambdaQuery().eq(PreErrorCode::getPreName, createCodeParam.getType()));
        String pre=one.getPreCode();

        //后四位 根据传入type生成
        RedisAtomicLong entityIdCounter = new RedisAtomicLong("errCode:" + createCodeParam.getType(), redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();
        //超出最大值，重置
        if(increment>9999){
            increment = 0L;
            entityIdCounter.set(1L);
        }

        ErrorCode errorCode = new ErrorCode(pre+formatNum(increment),pre);
        errorCodeService.save(errorCode);
        return errorCode.getErrorCode();
    }

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String CodeList(){

        List<ErrorCode> list = errorCodeService.list();

        return JSON.toJSONString(list);
    }


    @RequestMapping(value = "/update",method = RequestMethod.PUT)
    public String UpdateCode(@RequestBody UpdateCodeParam updateCodeParam){
        ErrorCode errorCode = new ErrorCode();
        BeanUtils.copyProperties(updateCodeParam,errorCode);
        errorCodeService.updateById(errorCode);
        return "ok" ;
    }


    private String formatNum(Long number){
        NumberFormat formatter = NumberFormat.getNumberInstance();
        formatter.setMinimumIntegerDigits(4);
        formatter.setGroupingUsed(false);
        return formatter.format(number);
    }
}
